<template>
  <el-card class="box-card">
    角色管理
    <hr>
    <br>
    <el-row style="display: flex;justify-content: flex-start;">
      <!--搜索框-->
      <span style="">
        <el-input v-model="keyword" style="width: 200px" placeholder="请输入角色名"
                  size="mini"></el-input>
        <el-button type="success" @click="selectTable" icon="el-icon-search"
                   v-has="'role:list'"
                   size="mini">搜索</el-button>
      </span>
      <!--新增按钮-->
      <span style="display: inline-block;margin-left: 30px">
        <el-button type="primary" icon="el-icon-circle-plus-outline"
                   @click="addDialog" size="mini"
                   v-has="'role:add'"
                   round>新增
        </el-button>
      </span>
    </el-row>


    <br>
    <br>
    <!--表格数据及操作-->
    <el-table :data="tableData" border style="width: 100%" stripe ref="multipleTable"
              tooltip-effect="dark">
      <!--索引-->
      <el-table-column type="index" :index="indexMethod">
      </el-table-column>
      <el-table-column prop="roleName" label="角色名" sortable>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" :formatter="dateForma">
      </el-table-column>
      <el-table-column prop="status" label="角色状态">

        <template slot-scope="scope">
          <el-switch v-model="scope.row.status"
                     disabled
                     active-value="1"
                     inactive-value="0">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="350">
        <template slot-scope="scope">
          <el-button type="warning" icon="el-icon-warning" size="mini"
                     v-has="'permission:relation'"
                     @click="relationPermission(scope.row)">
            关联权限
          </el-button>
          <el-button type="primary" icon="el-icon-edit" size="mini"
                     v-has="'role:upd'"
                     @click="editThis(scope.row)">
            编辑
          </el-button>
          <el-button type="danger"
                     v-has="'role:del'"
                     icon="el-icon-delete" size="mini" @click="removeThis(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <br>

    <!--分页条-->
    <el-pagination
      style="padding-top:15px"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="current"
      :page-sizes="[10, 20, 30]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>

    <el-dialog title="添加新角色" :visible.sync="dialogFormVisible">
      <el-form :model="form">
        <el-form-item label="角色名">
          <el-input v-model="form.roleName" placeholder="请输入角色名"></el-input>
        </el-form-item>
        <el-form-item label="角色状态">
          <el-switch v-model="switchon"></el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addNew">确 定</el-button>
      </div>
    </el-dialog>


    <el-dialog title="修改角色信息" :visible.sync="editdialog">
      <el-form :model="form">
        <el-form-item label="角色名">
          <el-input v-model="form.roleName" placeholder="请输入角色名"></el-input>
        </el-form-item>
        <el-form-item label="角色状态">
          <el-switch v-model="editSwitchon"></el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editdialog = false">取 消</el-button>
        <el-button type="primary" @click="updThis">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="关联权限" :visible.sync="permissionDialog">
      <el-form :model="form">
        <el-form-item label="角色名">
          <el-input v-model="form.roleName" disabled placeholder="请输入角色名"></el-input>
        </el-form-item>
        <el-tree
          :data="treData"
          show-checkbox
          node-key="id"
          ref="tree"
          default-expand-all
        >
        </el-tree>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="permissionDialog = false">取 消</el-button>
        <el-button type="primary" @click="addPermission">确 定</el-button>
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
  import moment from 'moment'

  export default {
    name: "role",
    data() {
      return {
        tableData: [],   //表格数据
        treData: [],
        backIds: [],
        keyword: '',   //查询输入框数据
        total: 0, // 总条数
        pageSize: 10,     // 每页显示的条数
        current: 1,  // 当前页码
        switchon: true,
        editSwitchon: true,
        checkStrictly: false,
        form: {
          roleName: '',
          status: true,
          id: ""
        },
        dialogFormVisible: false,
        editdialog: false,
        permissionDialog: false,
      }
    },
    methods: {
      /**
       * 日期格式化
       * @param row
       * @param column
       * @returns {string}
       */
      dateForma(row, column) {
        var date = row[column.property];
        if (date == undefined) {
          return ''
        }
        return moment(date).format("YYYY-MM-DD")
      },
      /**
       * 表格索引
       * @param index
       * @returns {*}
       */
      indexMethod(index) {
        return index;
      },
      /**
       * 监听数据表格每页条数变化并更新表格数据
       * @param val
       */
      handleSizeChange(val) {
        this.getTableDate(val, this.current, null);
      },
      /**
       * 监听页码变化并更新表格
       * @param val
       */
      handleCurrentChange(val) {
        this.getTableDate(this.limit, val, null);
      },
      /**
       * 关键字查询
       */
      selectTable() {
        this.getTableDate(this.limit, this.current, this.keyword);
      },
      /**
       * 获取表格数据
       * @param limit
       * @param page
       * @param keyword
       */
      getTableDate(limit, page, keyword) {
        this.$axios({
          method: 'post',
          headers: {
            'Content-Type': 'application/json'
          },
          url: 'http://127.0.0.1:8080/role/listAllRole',
          data: {
            limit: limit,
            page: page,
            username: keyword
          }
        }).then((response) => {
          this.tableData = response.data.data.records;
          this.total = response.data.data.total; //totalcount
          this.current = response.data.data.current; //页数
        }).catch((error) => {
          console.log(error)
        })
      },
      /**
       * 添加新角色
       */
      addNew() {
        if (this.switchon == true) {
          this.form.status = 1
        } else {
          this.form.status = 0
        }
        this.$axios({
          method: 'post',
          headers: {
            'Content-Type': 'application/json'
          },
          url: 'http://127.0.0.1:8080/role/addRole',
          data: {
            roleName: this.form.roleName,
            status: this.form.status,
            createBy: window.localStorage.getItem("uId")
          }
        }).then((response) => {
          if (response.data.msg == "添加成功！") {
            this.$message.success(response.data.msg);
            this.clearValue()
            this.dialogFormVisible = false;
            this.getTableDate(this.pageSize, this.current);
          } else {
            this.$message.error(response.data.msg);
          }
        }).catch((error) => {
          console.log(error)
        })
      },
      /**
       * 删除当前角色
       * @param row
       */
      removeThis(row) {
        this.$axios({
          method: 'delete',
          url: 'http://127.0.0.1:8080/role/delRole?id=' + row.id,
        }).then((response) => {
          if (response.data.msg == "删除成功！") {
            this.$message.success(response.data.msg);
            this.getTableDate(this.pageSize, this.current);
          } else {
            this.$message.error(response.data.msg);
          }
        }).catch((error) => {
          console.log(error)
        })
      },
      /**
       * 打开添加弹出层
       */
      addDialog() {
        this.clearValue()
        this.dialogFormVisible = true;
      },
      /**
       * 打开编辑弹出层
       * @param row
       */
      editThis(row) {
        this.clearValue()
        this.form.id = row.id;
        this.editdialog = true;
        this.form.roleName = row.roleName;
        if (row.status == 0) {
          this.form.status = false;
          this.editSwitchon = false
        } else {
          this.form.status = true;
          this.editSwitchon = true;
        }
      },
      /**
       * 更新当前角色
       */
      updThis() {
        if (this.switchon == true) {
          this.form.status = 1
        } else {
          this.form.status = 0
        }
        this.$axios({
          method: 'put',
          headers: {
            'Content-Type': 'application/json'
          },
          url: 'http://127.0.0.1:8080/role/updRole',
          data: {
            id: this.form.id,
            roleName: this.form.roleName,
            status: this.form.status,
            updateBy: window.localStorage.getItem("uId")
          }
        }).then((response) => {
          if (response.data.msg == "更新成功！") {
            this.$message.success(response.data.msg);
            this.clearValue()
            this.editdialog = false;
            this.getTableDate(this.pageSize, this.current);
          } else {
            this.$message.error(response.data.msg);
          }
        }).catch((error) => {
          console.log(error)
        })
      },
      /**
       * 清空弹层值
       */
      clearValue() {
        Object.keys(this.form).forEach((key) => (this.form[key] = ''))
      },
      /**
       * 角色关联权限
       */
      relationPermission(row) {
        this.form.id = row.id;
        this.form.roleName = row.roleName;
        this.backIds = [];
        this.$axios({
          method: 'get',
          headers: {
            'Content-Type': 'application/json'
          },
          url: 'http://127.0.0.1:8080/permission/getRolePermission?rId=' + row.id,
        }).then((response) => {
          this.permissionDialog = true;
          const backData = response.data.data;
          for (let i = 0; i < backData.length; i++) {
            var num = 0;
            for (let j = 0; j < backData.length; j++) {
              if (backData[i].id != backData[j].pid) {
                num += 1;
                if (num == backData.length) {
                  this.backIds.push({id: backData[i].id});
                }
              }
            }
          }
          this.$nextTick(() => {
            this.$refs.tree.setCheckedNodes(this.backIds);
          });
          var t;
          clearTimeout(t)
          t = setTimeout(function () {

          }, 2000);

        }).catch((error) => {
          console.log(error)
        })
      },
      getPermissionDate() {
        this.$axios({
          method: 'post',
          headers: {
            'Content-Type': 'application/json'
          },
          url: 'http://127.0.0.1:8080/permission/listAllPermission',
          data: {}
        }).then((response) => {
          // this.treData = response.data.data;
          var json = response.data.data;
          let arr1 = JSON.parse(JSON.stringify(json).replace(/permissionName/g, "label"))
          arr1 = JSON.parse(JSON.stringify(arr1).replace(/childs/g, "children"))
          this.treData = arr1;
        }).catch((error) => {
          console.log(error)
        })
      },
      addPermission() {
        this.$axios({
          method: 'post',
          headers: {
            'Content-Type': 'application/json'
          },
          url: 'http://127.0.0.1:8080/permission/relationPermission',
          data: {
            rId: this.form.id,
            pId: this.$refs.tree.getCheckedKeys()
          }
        }).then((response) => {
          if (response.data.msg == "添加成功！") {
            this.$message.success("关联权限成功~！");
            this.permissionDialog = false;
          } else {
            this.$message.error(response.data.msg);
          }
        }).catch((error) => {
          console.log(error)
        })
      }
    },
    created() {
      /**
       * 页面渲染调用一次获取表格
       */
      this.getTableDate(this.pageSize, this.current);
      this.getPermissionDate();

    }
  }
</script>
